<template>
    <el-drawer :title="title" visible @close="$emit('close');$emit('load')" size="1200px" :wrapperClosable="false">
        <div class="add-main" v-loading="loading">
            <div class="btn-con">
                <el-button v-if="handleShow != 'detail'" type="primary" size="small" icon="el-icon-circle-check"
                    @click.native.prevent="submit()" :disabled="loading">提交
                </el-button>
            </div>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="title" label="主题名称">
                            <el-input style="width: 215px;" v-model="form.title" placeholder="请输入主题名称" clearable
                                size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="sub_title" label="副标题">
                            <el-input style="width: 215px;" v-model="form.sub_title" placeholder="请输入副标题" clearable
                                size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="图标" prop="cover">
                            <el-upload class="avatar-uploader" :action="$uploadUrl" :show-file-list="false"
                                :on-success="handleCoverSuccess" :on-error="handleUploadError">
                                <img v-if="form.cover" :src="form.cover" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="主题图片" prop="picture">
                            <el-upload class="avatar-uploader01" :action="$uploadUrl" :show-file-list="false"
                                :before-upload="beforeUpload1" :on-success="handleAvatarSuccess"
                                :on-error="handleUploadError">
                                <img v-if="form.picture" :src="form.picture" class="avatar0">
                                <i v-else class="el-icon-plus avatar-uploader-icon0"></i>
                                <div slot="tip" class="el-upload__tip text-error">请上传图片尺寸为750*420的图片</div>
                                <div slot="tip" class="el-upload__tip text-error">单文件大小请在1M以内,仅支持JPG、JPEG、PNG格式</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <div v-for="item,index in form.tableList" :key="index">
                        <el-col :span="24">
                            <el-form-item>
                                <el-divider></el-divider>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="商品分类" prop="cate_ids">
                                <el-cascader style="width: 600px;" class="form-item-cascader" :key="resetCascader"
                                    ref="myCascader" v-model="item.cate_ids" placeholder="请选择分类" :options="cateList"
                                    :props="optionProps" @change="e => handleChange(e, item.cate_ids, index)"
                                    clearable></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item prop="order_type" label="商品">
                                <el-select style="width: 800px;" v-model="item.order_type" placeholder="请选择一级商品分类" clearable
                                    size="small" multiple>
                                    <el-option v-for="dict in goodsLists[index]" :key="dict.code" :label="dict.name"
                                        :value="dict.code" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="排序">
                                <el-input style="width: 215px;" v-model="item.sort"
                                    @keyup.native="item.sort=handleNum(item.sort)" clearable size="small" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                <el-radio-group v-model="item.status">
                                    <el-radio label="0">正常</el-radio>
                                    <el-radio label="1">禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="分类图片">
                                <el-upload class="avatar-uploader01" :action="$uploadUrl" :show-file-list="false"
                                    :before-upload="beforeUpload" :on-success="res => handleItemAvatarSuccess(res, index)"
                                    :on-error="handleUploadError">
                                    <img v-if="item.picture" :src="item.picture" class="avatar0">
                                    <i v-else class="el-icon-plus avatar-uploader-icon0"></i>
                                    <div slot="tip" class="el-upload__tip text-error">请上传图片尺寸为750*300的图片</div>
                                    <div slot="tip" class="el-upload__tip text-error">单文件大小请在1M以内,仅支持JPG、JPEG、PNG格式</div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
    
                        <el-col :span="12" v-if="form.tableList.length > 1">
                            <el-form-item>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="del(index)">
                                    删除
                                </el-button>
                            </el-form-item>
                        </el-col>
                    </div>
                    <el-col :span="24">
                        <el-form-item>
                            <el-divider></el-divider>
                            <el-button size="mini" type="primary" icon="el-icon-plus" @click="addRow">
                                增加
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- <goods ref="goods" :handleShow="handleShow" :code="code" /> , getGoodsLists-->
        </div>
    </el-drawer>
</template>
<script>
import throttle from 'lodash.throttle'
import goods from "./detail/goods.vue"
import { setSceneInfo, getSceneInfo, getSceneCateLists, getGoodsLists } from '@/api/goods/scenarized.js';
import { getGoodsCateLists } from "@/api/goods/goods"
export default {
    name: '',
    props: {
        title: String,
        handleShow: {
            type: String, //add新增edit编辑
            default: ""
        },
        code: {
            type: String, //add新增edit编辑
            default: ""
        },
        data: {
            type: Object,
            default: function () {
                return {}
            }
        }
    },
    components: {
        goods,
    },
    data() {
        return {
            loading: false,
            GoodList: [],
            selectList: [],
            formLoading: false,
            form: {
                title: '',
                sub_title: '',
                cover: '',
                picture: '',
                tableList: [{
                    cate_ids: [],
                    order_type: '',
                    picture: "",
                    status: '0',
                    sort: ''
                }],
            },
            rules: {
                title: [{ required: true, message: '请输入主题名称', trigger: 'change' }],
                sub_title: [{ required: true, message: '请输入副标题', trigger: 'change' }],
                cover: [{ required: true, message: '请选择上传图片', trigger: 'change' }],
                picture: [{ required: true, message: '请选择上传图片', trigger: 'change' }],
                // cover: [{ required: true, message: '请选择上传图片', trigger: 'change' }],
                // cate_ids: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
                // order_type: [{ required: true, message: '请选择商品', trigger: 'change' }],
            },
            cateList: [],
            cateIds: [],
            orderTypeList: [],
            goodsLists: [],
            optionProps: {
                value: 'id',
                label: 'name',
                disabled: "disabled",
                children: 'children',
                emitPath: true,
            },
            resetCascader: 0,
        }
    },
    created() {
        let fun = [
            getGoodsCateLists()
        ]
        Promise.all(fun).then(ress => {
            this.cateList = ress[0].data
            this.cateList.forEach(e => {
                if (e && e.children) {
                    e.disabled = false
                } else {
                    e.disabled = true
                }
            });
            if (this.code) {
                this.loading = true
                getSceneInfo({ code: this.code }).then(res => {
                    console.log(res.data.items, 7777)
                    this.form.code = res.data.code
                    this.form.cover = res.data.cover
                    this.form.picture = res.data.picture
                    this.form.title = res.data.title
                    this.form.sub_title = res.data.sub_title
                    const formTableList = res.data.items.map(item => {
                        const oneCateId = item.one_cate.find(cate => cate.is_selected === 1).id || '';
                        const twoCateId = item.two_cate.find(cate => cate.is_selected === 1).id || '';
                        const orderType = item.goods_lists.filter(goods => goods.is_selected === 1).map(goods => goods.code);
                        const cateIds = [oneCateId, twoCateId];
                        return {
                            cate_ids: cateIds,
                            order_type: orderType,
                            cate_code: item.cate_code,
                            picture: item.picture,
                            status: String(item.status),
                            sort: item.sort,
                        };
                    });
                    this.form.tableList = formTableList;
                    this.loading = false
                }).catch(() => {
                    this.loading = false
                })

            }
        })
    },
    watch: {
        'form.tableList': {
            deep: true,
            handler(newTableList, oldTableList) {
                newTableList.forEach((item, index) => {
                    const oldCateIds = oldTableList[index] ? oldTableList[index].cate_ids : [];
                    const newCateIds = item.cate_ids || [];

                    // 检查 cate_ids 是否有变化
                    if (!this.areArraysEqual(oldCateIds, newCateIds)) {
                        this.handleChange(item.cate_ids, item.cate_ids, index);
                    }
                });
            }
        }
    },
    methods: {
        close() {
            this.form = {
                title: '',
                sub_title: '',
                cover: '',
                picture: '',
                tableList: [{
                    cate_ids: [],
                    order_type: '',
                    picture: "",
                    status: '0',
                    sort: ''
                }],
            }
            this.$emit('close')
            this.$emit('load')
        },
        addRow() {
            this.form.tableList.push({
                cate_ids: [],
                order_type: '',
                picture: "",
                status: '0',
                sort: ''
            });
        },
        del(index) {
            // 根据索引从 tableList 数组中删除对应的项目
            this.form.tableList.splice(index, 1);
        },
        // 辅助方法，用于检查两个数组是否相等
        areArraysEqual(arr1, arr2) {
            if (arr1.length !== arr2.length) {
                return false;
            }

            for (let i = 0; i < arr1.length; i++) {
                if (arr1[i] !== arr2[i]) {
                    return false;
                }
            }

            return true;
        },
        handleChange(id, cate_ids, index) {
            console.log(id, cate_ids, "id, cate_ids")
            this.form.cateids = cate_ids[1]
            let key_name = this.cateList.find(item => item.id == id[0]).name
            let list = this.cateList.find(item => item.id == id[0]).children
            let key_cate_name = list.find(item => item.id == id[1]).name
            let key_id = id[1]

            // 判断当前选择的商品分类是否在其他 tableList 中已经被选中
            const isCateSelected = this.form.tableList.some((item, i) => i !== index && item.cate_ids[1] === cate_ids[1]);

            // 如果已经被选中，则给出提示并清空当前选择
            if (isCateSelected) {
                this.$message.warning('该商品分类已在其他项中选择，请选择其他分类。');
                this.$set(this.form.tableList, index, { cate_ids: [], order_type: [] });
                return;
            }
            // key_name: key_name, page: 1, limit: 99999, key_status: 1, key_cate_name: key_cate_name
            getGoodsLists({ cate_id: key_id }).then(res => {
                this.$set(this.goodsLists, index, res.data);
            })
        },
        beforeUpload1(file, fileList) {
            this.loading = true;
            return new Promise((resolve, reject) => {
                if (file.size / (1024 * 1024) > 1) {  // 限制文件大小
                    this.$message.warning(`当前限制文件大小不能大于1M`)
                    return reject(false)
                }
                this.limitFileWH(750, 420, file).then((res) => {
                    file.isFlag = res
                    if (file.isFlag) {
                        return resolve(true)
                    } else {
                        this.loading = false;
                        return reject(false)
                    }
                })
            })
        },
        beforeUpload(file, fileList) {
            this.loading = true;
            return new Promise((resolve, reject) => {
                if (file.size / (1024 * 1024) > 1) {  // 限制文件大小
                    this.$message.warning(`当前限制文件大小不能大于1M`)
                    return reject(false)
                }
                this.limitFileWH(750, 300, file).then((res) => {
                    file.isFlag = res
                    if (file.isFlag) {
                        return resolve(true)
                    } else {
                        this.loading = false;
                        return reject(false)
                    }
                })
            })
        },
        handleAvatarSuccess(res, file) {
            this.$set(this.form, 'picture', res.data[0].fileurl)
            this.loading = false;
        },
        handleItemAvatarSuccess(res, index) {
            const item = this.form.tableList[index];
            this.$set(item, 'picture', res.data[0].fileurl);
            this.loading = false;
        },
        handleCoverSuccess(res, file) {
            // this.$set(this.form, 'cover', res.data[0].fileurl)
            this.$set(this.form, 'cover', res.data[0].fileurl)
            this.loading = false;
        },
        handleUploadError() {
            this.loading = false;
        },
        getGoods(id) {
            this.suppId = id
            this.goodsShow = true
            this.$nextTick(() => {
                this.$refs.goods.goodsList = []
            })
        },
        submit: throttle(function () {
            console.log(this.form.tableList, "111")
            // 首先进行表单的基本验证
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const isValidTableList = this.form.tableList.every((item, index) => {
                        // 验证商品分类是否选择
                        if (!item.cate_ids || item.cate_ids.length === 0) {
                            this.$message.error(`第${index + 1}项：请选择商品分类`);
                            return false;
                        }
                        // 验证商品是否选择
                        if (!item.order_type || item.order_type.length === 0) {
                            this.$message.error(`第${index + 1}项：请选择商品`);
                            return false;
                        }
                        // 验证排序是否填写
                        if (!item.sort) {
                            this.$message.error(`第${index + 1}项：请填写排序`);
                            return false;
                        }

                        // 验证状态是否选择
                        if (item.status === undefined || item.status === null) {
                            this.$message.error(`第${index + 1}项：请选择状态`);
                            return false;
                        }

                        // 验证分类图片是否上传
                        if (!item.picture) {
                            this.$message.error(`第${index + 1}项：请上传分类图片`);
                            return false;
                        }
                        return true;
                    });
                    // 如果所有验证通过，则继续提交
                    if (isValidTableList) {
                        console.log(this.form, 1111)
                        const newDataArray = this.form.tableList.map((item) => {
                            return {
                                picture: item.picture,
                                sort: item.sort,
                                status: item.status,
                                cate_code: item.cate_code ? item.cate_code : '',
                                cate_id: item.cate_ids[1],
                                goods_codes: item.order_type.join(',')
                            };
                        });
                        let json = {
                            title: this.form.title,
                            sub_title: this.form.sub_title,
                            cover: this.form.cover,
                            picture: this.form.picture,
                            code: this.form.code ? this.form.code : '',
                            data_json: JSON.stringify(newDataArray)
                        }
                        setSceneInfo(json)
                            .then(res => {
                                this.msgSuccess(res.info);
                                this.loading = false;
                                this.close();
                            })
                            .catch(() => {
                                this.loading = false;
                            });
                    }
                }
            });
        }, 1000, { trailing: false }),
    },
}

</script>
<style scoped lang='scss'>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    /* text-align: center;
    display: block !important; */
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.avatar0 {
    width: 250px;
    height: 100px;
    display: block;
}
// .avatar1 {
//     width: 350px;
//     height: 100px;
//     display: block;
// }
.avatar-uploader0 .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 250px;
    height: 100px;
}

.avatar-uploader0 .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon0 {
    font-size: 28px;
    color: #8c939d;
    width: 250px;
    height: 100px;
    line-height: 100px;
    /* text-align: center;
    display: block !important; */
}

.avatar-uploader01 {
    /deep/.el-upload--text {
        width: 250px;
        height: 100px;
        line-height: 100px;
    }
}
</style>